package com.dream.antiquities.utils

import android.content.Context
import android.net.Uri
import java.io.*

object CopyFileByUri {
    fun getPath(context: Context, srcUri: Uri): String {
        val path = context.filesDir.toString() + "/${System.currentTimeMillis()}.png" //获取本地目录
        val file = File(path)
        return try {
            val inputStream = context.contentResolver.openInputStream(
                srcUri
            ) ?: return "null" //context的方法获取URI文件输入流
            val outputStream: OutputStream = FileOutputStream(file)
            copyStream(inputStream, outputStream) //调用下面的方法存储
            inputStream.close()
            outputStream.close()
            path //成功返回路径
        } catch (e: Exception) {
            e.printStackTrace()
            "null" //失败返回路径null
        }
    }

    private fun copyStream(input: InputStream, output: OutputStream) { //文件存储
        val BUFFER_SIZE = 1024 * 2
        val buffer = ByteArray(BUFFER_SIZE)
        val `in` = BufferedInputStream(input, BUFFER_SIZE)
        val out = BufferedOutputStream(output, BUFFER_SIZE)
        var count = 0
        var n = 0
        try {
            while (`in`.read(buffer, 0, BUFFER_SIZE).also { n = it } != -1) {
                out.write(buffer, 0, n)
                count += n
            }
            out.flush()
            out.close()
            `in`.close()
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }



}